<?php
namespace Addons\QyWechat\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\QyWechat\Helper;
use Addons\QyWechat\Services\QyWechatApi;

class Reply extends BaseAdmin
{	
    public function quick_reply(){
		$wid = Session::get('wid');
		$quickReply = new Model('qy_quick_reply_list');
		$group = (new Model('qy_quick_reply_group'))->field("keyid,name")->list_all_array();
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		//类型查询 
		$type = $_GET['type'];
		if(trim($type)!=''){
			$where['type'] = $type;
		}
		$groups = $_GET['group'];
		if(trim($groups)!=''){
			$where['groupid@~'] = $groups;
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($quickReply->where($where)->order('id desc'));
		foreach($res as $k=>$v){
			if($v->type == 1){
				$typeMsg = '文本';
			}elseif($v->type == 2){ 
				$typeMsg = '图片';
			}elseif($v->type == 3){
				$typeMsg = '视频';
			}elseif($v->type == 4){
				$typeMsg = '文件';
			}elseif($v->type == 5){
				$typeMsg = '链接';
			}elseif($v->type == 6){
				$typeMsg = '图文';
			}
			$res[$k]->typeMsg = $typeMsg;
            $res[$k]->text_content = json_decode($v->text_content,1);
		}
		$h = Helper::getInstance();
		// $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		$replyConfig = $h->get_message_send_config($wid);
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$toolbarUrl = $h->get_http_server_name().'/Addons/QyWechat/H5/Reply/index.html?corp_id='.$qyConfig->corp_id.'&agent_id='.$replyConfig->agent_id;
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		$this->assign("group", $group);
		$this->assign("type", $type);
		$this->assign("toolbarUrl", $toolbarUrl);
		return $this->show();
	}

	public function update_order(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST["id"];
		$order = $_POST["order"];
		$radar_list = (new Model('qy_quick_reply_list'))->find($id);
		$radar_list->orders = $order;
		if($radar_list->save()){
			sendSuccess("修改成功");
		}sendError("修改失败");
	}

	public function add_quick_reply(){
		$wid = Session::get('wid');
		$quickReply = new Model('qy_quick_reply_list');
		if(\Request::get(1)){
			$quickReply->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			if(!$quickReply->id){
				$quickReply->wid = $wid;
				$quickReply->ctime = date('Y-m-d H:i:s');
			}
			$quickReply->name = $_POST['name'];
			$quickReply->type = $_POST['shareType'];
			$quickReply->groupid = json_encode(explode(',',$_POST['selectedGroup']),320);
			$quickReply->text_content = json_encode($_POST['text_content']); 
			$quickReply->pic_path = $_POST['pic'];
			$quickReply->video_path = $_POST['video_path'];
			$quickReply->video_name = $_POST['video_name'] ?: '自定义视频';
			$quickReply->file_path = $_POST['file_path'];
			$quickReply->file_name = $_POST['file_name'];
			$quickReply->link_url = $_POST['link_url'];
			$quickReply->link_title = $_POST['link_title'];
			$quickReply->link_pic = $_POST['link_pic'];
			$quickReply->link_desc = $_POST['link_desc'];
			$quickReply->characters = $_POST['characters'];
			$quickReply->drawing = $_POST['drawing'];
			if($quickReply->save()){
				sendSuccess('操作成功');
			}
		} 
		$group = new Model('qy_quick_reply_group');
		$grouparr = $group->where(array('wid'=>$wid))->map_array('keyid', 'name');
		$this->assign("quickReply", $quickReply);
		$this->assign("grouparr", $grouparr);
		return $this->show();
	}
	
	public function upload_file(){
		setApi();
		$path = './qy';
		$field = 'file';
		// sendSuccess($_FILES);
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) == 'php') {
            sendError('禁止的文件后缀');
        }
		// 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
		$path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);

		if($saveImg){
			$filePath = $saveImg ? $path : $saveImg;
			$filePath = get_host(strstr($filePath,'qy'));
			sendSuccess('上传成功',['filePath'=>$filePath,'fileName'=>$_FILES[$field]["name"]]);
		}else{
			sendError('上传失败');
		}
	}
	public function upload_file_huashu(){
		setApi();
		$path = './qy';
		$field = 'file';
		// sendSuccess($_FILES);
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) == 'php') {
            sendError('禁止的文件后缀');
        }
		// 创建文件夹
        try {
            mkdir($path);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
		$path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);

		if($saveImg){
			$filePath = $saveImg ? $path : $saveImg;
			sendSuccess('上传成功',['filePath'=>$filePath,'fileName'=>$_FILES[$field]["name"]]);
		}else{
			sendError('上传失败');
		}
	}
	
	public function del_quick_reply(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		if($id){
			$quickReply = (new Model('qy_quick_reply_list'))->find($id);
		}else{
			sendError('参数错误');
		}
		$quickReply->delete();
		sendSuccess('操作成功');
	}
	
	public function quick_reply_steps(){
		$wid = Session::get('wid');
		$h = Helper::getInstance();
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		$confing = (new Model('qy_party_confing'))->find(['wid'=>$wid]);
		if(is_post()){
			setApi();
			$confing = (new Model("qy_party_confing"))->find(["wid"=>$wid]);
			if(!$confing->id){
				$is_set = (new Model("qy_party_confing"))->find(["qy_appid"=>$_POST["qy_appid"]]);
				if($is_set->id){
					sendError("企业appid已被注册，不能重复注册");
				}
				$confing = new Model("qy_party_confing");
				$confing->wid = $wid;
			}
			$is_set = (new Model("qy_party_confing"))->find(["qy_appid"=>$_POST["qy_appid"],"id@!="=>$confing->id]);
			if($is_set->id){
				sendError("企业appid已被注册，不能重复注册");
			}
			$confing->qy_appid = $_POST["qy_appid"];
			if($confing->save()){
				sendSuccess("操作成功");
			}sendError("操作失败");
		}
		$this->assign("h", $h);
		$this->assign("replyConfig", $replyConfig);
		$this->assign("confing", $confing);
		return $this->show();
	}
	
	public function upload_txt(){
		setApi();
		$field = 'file';
		if (!$_FILES[$field]) sendError('文件不存在');
		$ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        if (strtolower($ext) != 'txt') {
            sendError('上传文件不合法');
        }
		$path = './'.$_FILES[$field]["name"];
		if(!file_exists($path)){
			$saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
			if($saveImg){
				$filePath = $saveImg ? $path : $saveImg;
				sendSuccess('上传成功',['filePath'=>$filePath,'fileName'=>$_FILES[$field]["name"]]);
			}else{
				sendError('上传失败');
			}	
		}else{
			 sendError('文件已存在');
		}
	}
	
	public function quick_reply_set(){
		$wid = Session::get('wid');
		$config = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
		if(is_post()){
			setApi();
			$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
			$QyWechatApi = QyWechatApi::getInstance();
			$agentApp = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$_POST['agent_id'],$_POST['secret']);
			$appInfo = $agentApp->agent->get($_POST['agent_id']);
			if($appInfo['errcode'] == 0){
				if(!$config->id){
					$config->wid = $wid;
					$config->ctime = date('Y-m-d H:i:s');
				}
				$config->agent_id = $_POST['agent_id'];
				$config->secret = $_POST['secret'];
				$config->name = $appInfo['name'];
				$config->square_logo_url = $appInfo['square_logo_url'];
				$config->description = $appInfo['description'];
				if($config->save()){
					sendSuccess('操作成功',$config);
				}else{
					sendError('数据库操作失败');
				}
			}else{
				sendError('操作失败:请检查配置');
			}
		}
		$this->assign("config", $config);
		return $this->show();
	}
	
	public function group_manage(){
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		//name 模糊查询
		$name = $_GET['name'];
		if(trim($name)!=''){
			$where['name@~'] = $name;	
		}
		$where['wid'] = $wid;
		$p = new \Pagination();		
		$res = $p->model_list($group->where($where)->order('sort'));
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign("res", $res);
		$this->assign("name", $name);
		return $this->show();
	}
	
	public function del_group(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		if($id){
			$group = (new Model('qy_quick_reply_group'))->find($id);
		}else{
			sendError('参数错误');
		}
		$group->delete();
		sendSuccess('操作成功');
	}
	
	public function add_group(){
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		if(\Request::get(1)){
			$group->find(\Request::get(1));
		}
		if(is_post()){
			setApi();
			if(!$group->id){
				$group->wid = $wid;
				$group->ctime = time();
				$is_check = (new Model('qy_quick_reply_group'))->find(["name"=>$_POST['name']]);
				if($is_check->id){
					sendError("名称已存在");
				}
			}
			$is_check = (new Model('qy_quick_reply_group'))->find(["name"=>$_POST['name'],"id@!="=>$group->id]);
			if($is_check->id){
				sendError("名称已存在");
			}
			$group->name = $_POST['name'];
			$group->sort = $_POST['sort'];
			$rs = $group->save();
			if($rs->id){
				$rs->keyid = 'C'.$rs->id.'J';
				$rs->save();
				sendSuccess('操作成功');
			}
		}
		$this->assign("group", $group);
		return $this->show();
	}

	public function check_name($groups){
		$keyid = json_decode($groups,1);
		$group = array_column((new Model('qy_quick_reply_group'))->where(["keyid"=>$keyid])->field("name")->list_all_array(),"name");
		return implode(",", $group);
	}
	
	public function select_group(){
		$wid = Session::get('wid');
		if(\Request::get('name')){
			$where['name@~'] = \Request::get('name');
		}
		$where['wid'] = $wid;
		$group = (new Model('qy_quick_reply_group'))->where($where)->order('sort')->list_all_array();
		$this->assign("group", $group);
		$this->assign("count", count($group));
		$this->assign("name", \Request::get('name'));
		return $this->show();
	}

	public function daoru_huashu(){
		$wid = Session::get('wid');
		if(is_post()){
			//引入excel组件
			header("Content-Type:application/json;charset=utf-8");
			require_once DOXCX_FRAME_PATH . '/fun/library/PHPExcel.php';
			require_once DOXCX_FRAME_PATH . "/fun/library/PHPExcel/IOFactory.php";
			require_once DOXCX_FRAME_PATH . '/fun/library/PHPExcel/Reader/Excel5.php';

			$fileName = $_POST['file_name'];
			$filePath = $_POST['file_path'];

			if(!$filePath){
				sendError('请上传表格');
			}
			$objReader = new \PHPExcel_Reader_Excel2007();
			$objPHPExcel = $objReader ->load($filePath);
			$data = $objPHPExcel->getActiveSheet()->toArray();

			$sheet = $objPHPExcel->getSheet(0);
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数

			$contents = [];
			// sendSuccess('sssss',$data);
			// 重第六行开始读取
			for($j=6;$j<=count($data);$j++) {
				$name = $data[$j-1][0]; //获取A列的值
				$content = $data[$j-1][1];
				$fenzu = $data[$j-1][8];
				if($content){
					$contents[] = [$content,$fenzu,$name];
				}
			}
			unlink($filePath);//删除文件
			// sendSuccess('sssss',$contents);
			// 
			$resdata = '';
			$ok = [];
			$error = [];
			foreach ($contents as $k => $val) {
				$quickReply = new Model('qy_quick_reply_list');
				if($val){
					$quickReply->wid = $wid;
					$quickReply->ctime = date('Y-m-d H:i:s');
					$quickReply->name = $val[2];
					$quickReply->type = 1;
					$quickReply->groupid = json_encode($this->get_group_keyid($val[1]));
					$quickReply->text_content = json_encode($val[0]);
					// sendSuccess($quickReply->save());
					if($quickReply->save()){
						// sendSuccess('操作成功');
						$ok[] = $k+1; 
					}else{
						$error[] = $k+1;
					}

				}
			}
			if($error){
				sendSuccess('导入失败条目:'.implode(',', $error));
			}else{
				sendSuccess('操作成功');
			}
			
		}
		return $this->show();
	}

	public function huashu_download_excel(){
		$filePath = DOXCX_FRAME_PATH . '/Addons/QyWechat/View/static/reply/qiyehuashudaorumuban-v5.xlsx';
		//设置头信息
		header('Content-Disposition:attachment;filename=Excel企业话术导入模板 .xlsx');
		header('Content-Length:' . filesize($filePath));
		//读取文件并写入到输出缓冲
		readfile($filePath);
	}

	private function get_group_keyid($name=''){
		$result = [];
		$wid = Session::get('wid');
		$group = new Model('qy_quick_reply_group');
		if(!empty($name)){
			$namearr = explode(',', trim($name));
			foreach ($namearr as $namea) {
				if($group->has(['wid'=>$wid, 'name'=>trim($namea)])){
					$keyidm = $group->find(['wid'=>$wid, 'name'=>trim($namea)]);
					$result[] = $keyidm->keyid;
				}else{
					$group->name = $namea;
					$group->wid = $wid;
					$group->ctime = time();
					$group->sort = 0;
					$rs = $group->save();
					// sendSuccess($rs);
					if($rs->id){
						$rs->keyid = 'C'.$rs->id.'J';
						$rs->save();
						$result[] = $rs->keyid;
					}
				}
			}		
		}
		return $result;
	}
	
}